import { reqLogin, reqLoginMpWx, reqLoginChooseRole, reqUserInfo } from '@/api/user/index.js'
import { StorageHelper } from '@/utils/storage.js'

const userStorage = new StorageHelper('user')

const state = {
	token:  userStorage.get('token') || '',
	userInfo: userStorage.get('userInfo') || {},
	userAgree: userStorage.get('userAgree') || false,
}

const actions = {
	// 微信小程序一键授权登录(获取用户基本信息)
	 LoginMpWx({commit},{code,userInfo}) {
	  return new Promise((resolve, reject) => {
			//处理成服务器需要得数据
			let userInfoParams = {}
			userInfoParams.userCity = userInfo.city,
			userInfoParams.userGender = userInfo.gender == 0?'男':'女',
			userInfoParams.userHead = userInfo.avatarUrl,
			userInfoParams.username = userInfo.nickName,
			userInfoParams.userProvince = userInfo.province,
			userInfoParams.code = code
			userInfoParams.phone = 19859771591
       reqLoginMpWx(userInfoParams).then(response => {
					if(response.code == 200){
						 const {token} = response.body
						 state.token = token
						 state.userInfo = userInfo
						 commit('SET_TOKEN', token)
						 commit('SET_USERINFO',userInfo)
						 resolve(response)
					} else{
						reject(response.error)
					}
	      })
	  })		
	},
	// 手机号密码登录
	Login({ commit }, data) {
		return new Promise((resolve, reject) => {
			reqLogin(data).then(res => {
				if (res.code === 200) {
					const token = res.body
					commit('SET_TOKEN', token)
					reqUserInfo().then(re => {
						commit('SET_USERINFO', re.body)
						resolve(re)
					})
				} else {
					reject(res.body)
				}
			})
		})
	}
}

const mutations = {
	SET_TOKEN: (state, token) => {
		state.token = token
		userStorage.set('token', token)
	},
	SET_USERINFO:(state,userInfo)=>{
		state.userInfo = userInfo
		userStorage.set('userInfo', userInfo)
	},
	SET_USERAGREE:(state,userAgree)=>{
		state.userAgree = userAgree
		userStorage.set('userAgree', userAgree)
	}
}

const getters = {
	getToken: state => state.token,
	getUserInfo: state => state.userInfo,
	getUserAgree: state => state.userAgree,
}

export default {
	namespaced: true,
	state,
	actions,
	mutations,
	getters
}